/**
 * @description service cache
 *
 * @author xiaomi
 */

const moment = require('moment');
const Promise = require('bluebird');
const {client: redis} = require('./redis');

const parseJSON = require('../utils/parse-json-safe');

const UPDATE_TTL = 3 * 24 * 60 * 60;

module.exports = {
    realKey(key) {
        return `cache:${key}`;
    },
    set(key, value, ttl = 0) {
        key = this.realKey(key);

        return Promise.try(() => {
            if(typeof value === 'object') {
                value = JSON.stringify(value);
            }

            return redis.set(key, value);
        })
        .tap(() => {
            if(ttl > 0) {
                return redis.expire(key, ttl);
            }
        });
    },
    get(key, dataType = 'text') {
        key = this.realKey(key);

        return Promise.try(() => {
            return redis.get(key);
        })
        .then(data => {
            if(dataType === 'json') {
                return parseJSON(data);
            }

            return data;
        });
    },
    remove(key) {
        key = this.realKey(key);

        return Promise.try(() => {
            return redis.del(key);
        });
    },

    addUpdate(category, id, time = Date.now()) {
        const day = moment().format('YYYYMMDD');
        const key = `cache:update:${category}:${day}`;

        // 精确到秒
        const score = Math.floor(time / 1000);

        return Promise.try(() => {
            return redis.zadd(key, score, id);
        })
        .then(() => {
            return redis.ttl(key);
        })
        .then(ttl => {
            if(ttl === -1) {
                return redis.expire(key, UPDATE_TTL);
            }
        })
        .then(() => {
            return score;
        });
    }
};
